import socket
import sys
import logging

# 设置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def send_data(client_socket, data):
    """发送数据到服务器，并处理可能的异常"""
    try:
        client_socket.sendall(data.encode('utf-8'))
        logging.info("发送成功")
    except Exception as e:
        logging.error(f"发送数据时发生异常：{e}")
        raise


def receive_data(client_socket):
    """接收服务器数据，并处理可能的异常"""
    try:
        response = client_socket.recv(1024)
        if response:
            return response.decode('utf-8', errors='replace')
        else:
            return None
    except socket.timeout:
        logging.warning("接收数据时连接超时")
        return None
    except Exception as e:
        logging.error(f"接收数据时发生异常：{e}")
        return None


def handle_connection(client_socket, server_address):
    try:
        client_socket.connect(server_address)
        send_data(client_socket, "auth:我是客户端")

        while True:
            response = receive_data(client_socket)
            if not response:
                break
            print("接受到服务器端的数据：", response)

            user_input = input("请输入发送给服务端的数据：")
            if user_input.strip() == 'bye':
                break
            send_data(client_socket, user_input)
            print("发送成功，等待服务端信息")
    except socket.timeout:
        print("连接超时")
    except ConnectionAbortedError:
        print("连接被终止")
    except ConnectionResetError:
        print("连接被重置")
    except Exception as e:
        print(f"发生未知错误：{e}")
    finally:
        try:
            client_socket.close()
        except Exception as e:
            logging.error(f"关闭套接字时发生异常：{e}")


def main():
    server_address = ("127.0.0.1", 8887)
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
            handle_connection(client_socket, server_address)
    except Exception as e:
        logging.error(f"无法建立连接：{e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
